﻿using Coldairarrow.Business.Base;
using Coldairarrow.Business.Base_Manage;
using Coldairarrow.Entity;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.Base_Manage
{
    [Route("/Base_Manage/[controller]/[action]")]
    public partial class Base_UserController : BaseApiController
    {
        #region DI

        public Base_UserController(IBase_UserBusiness userBus, IOperator op, IOperatorDept Dept)
        {
            _userBus = userBus;
            _Op = op;
            _Dept = Dept;
        }

        IBase_UserBusiness _userBus { get; }
        IBase_QrCodeTypeBusiness _Base_QrCode { get; }
        IOperator _Op { get; }
        IOperatorDept _Dept { get; }
        #endregion

        #region 获取

        [HttpPost]
        public async Task<PageResult<Base_UserDTO>> GetDataList(PageInput<Base_UsersInputDTO> input)
        {
            return await _userBus.GetDataListAsync(input);

        }
        /// <summary>
        /// 根据角色获取用户列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<UserRole>>GetUserRoleDataList(PageInput<ConditionDTO> input)
        
        {
            var list = await _userBus.GetUserRoleDataListAsync(input);
            return list;

        }

        [HttpPost]
        public async Task<PageResult<Base_UserDTO>> GetDataListAsyncUser(PageInput<Base_UsersInputDTO> input)
        {
            return await _userBus.GetDataListAsyncUser(input);
        }
        [HttpPost]
        public async Task<PageResult<Base_User>> GetUserDataList(PageInput<ConditionDTO> input)
        {
            return await _userBus.GetDataListAsyncs(input);
        }

        [HttpPost]
        public async Task<Base_UserDTO> GetTheData(IdInputDTO input)
        {
            return await _userBus.GetTheDataAsync(input.id) ?? new Base_UserDTO();
        }

        /// <summary>
        /// 通过用户id 查询信息
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<Base_UserDTO>> SelectUserID(string ID)
        {
            var res = await _userBus.SelectUserID(ID);
            return res;
        }
        [HttpPost]
        public async Task<List<Base_UserDTO>> Selectid(string ID)
        {
            var res = await _userBus.Selectid(ID);
            return res;
        }
        [HttpPost]
        public async Task<List<UserRoleImage>> GetDataListByDeptuserid(PageInput<ConditionDTO> input)
        {
            var res = await _userBus.GetDataListByDeptuserid(input);
            return res;
        }
        [HttpPost]
        public async Task<List<Base_UserDTO>> SelectUser()
        {
            var res = await _userBus.SelectUser();
            return res;
        }
        [HttpPost]
        public async Task<List<SelectOption>> GetOptionList(OptionListInputDTO input)
        {
            return await _userBus.GetOptionListAsync(input);
        }

        #endregion

        #region 提交

        [HttpPost]
        public async Task SaveData(UserEditInputDTO input)
        {
            //bq.Result.
            if (!input.newPwd.IsNullOrEmpty())
                input.Password = input.newPwd.ToMD5String();
            if (input.Id.IsNullOrEmpty())
            {
                InitEntity(input);

                await _userBus.AddDataAsync(input);
            }
            else
            {
                await _userBus.UpdateDataAsync(input);
            }
        }


        /// <summary>
        /// 修改头像
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task SaveDataImg(Base_User input)
        {
            await _userBus.UpdateImgAsync(input);
        }





        [HttpPost]
        public async Task DeleteData(List<string> ids)
        {
            await _userBus.DeleteDataAsync(ids);
        }

        [HttpPost]
        public async Task<List<UserTreeDTO>> GetTreeUserListAsyncs()
        {
            return await _userBus.GetTreeUserListAsyncs();
        }

        /// <summary>
        /// 用户数据导入 
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<AjaxResult> Import(IFormFile file)
        {
            string ReturnValue = string.Empty;
            bool flag = true;
            try
            {
                #region 检查文件
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                var DataUser = new List<Base_User>();//存储用户数据
                var DataRole = new List<Base_UserRole>();//存储用户角色数据
                var liststr = new List<string>();
                MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                IWorkbook book;
                if (fileExt == ".xlsx")
                {
                    book = new XSSFWorkbook(ms);
                }
                else if (fileExt == ".xls")
                {
                    book = new HSSFWorkbook(ms);
                }
                else
                {
                    book = null;
                }
                ISheet sheet = book.GetSheetAt(0);

                int CountRow = sheet.LastRowNum + 1;//获取总行数

                if (CountRow - 1 == 0)
                {
                    return Error("Excel列表数据项为空!");

                }
                #endregion
                #region 循环验证
                for (int i = 1; i < CountRow; i++)
                {
                    //获取第i行的数据
                    var row = sheet.GetRow(i);
                    if (row != null)
                    {
                        //循环的验证单元格中的数据
                        for (int j = 0; j < 6; j++)
                        {
                            if ((j == 4 || j == 5) || (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0))
                            {
                                //return Error(ReturnValue += $"注意第{i + 1}行,第{j + 1}列数据为空。");
                            }
                            else
                            if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                            {
                                flag = false;
                                return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                            }
                        }
                    }
                }
                #endregion
                #endregion
                if (flag)
                {

                    for (int i = 0; i < CountRow; i++)
                    {
                        if (i != 0)
                        {
                            ///创建用户对象
                            Base_User Entity = new Base_User();
                            Base_UserRole role = new Base_UserRole();
                            var row = sheet.GetRow(i);

                            if (row.GetCell(0) != null && row.GetCell(0).ToString().Trim().Length > 0)
                            {
                                Entity.Id = IdHelper.GetId();
                                Entity.CreateTime = DateTime.Now;//当前系统时间
                                Entity.CreatorId = _Op.UserId;
                                Entity.Deleted = false;
                                Entity.EmployeStatus = false;
                                Entity.QrCode = "01," + Entity.Id;
                                Entity.UserCode = row.GetCell(0).ToString();
                            }

                            if (row.GetCell(1) != null && row.GetCell(1).ToString().Trim().Length > 0)
                            {
                                Entity.UserName = row.GetCell(1).ToString();
                            }
                            else {
                                Entity.UserName =null;
                            }
                            if (row.GetCell(2) != null && row.GetCell(2).ToString().Trim().Length > 0)
                            {
                                Entity.Password = GetMD5(row.GetCell(2).ToString()); 
                            }
                            else {

                                Entity.Password = null;
                            }

                            if (row.GetCell(3) != null && row.GetCell(3).ToString().Trim().Length > 0)
                            {
                                Entity.RealName = row.GetCell(3).ToString();
                            }

                            if (row.GetCell(4) != null && row.GetCell(4).ToString().Trim().Length > 0)
                            {
                                Entity.Sex = row.GetCell(4).ToString() == "男" ? Sex.Man : Sex.Woman;
                            }

                            if (row.GetCell(5) != null && row.GetCell(5).ToString().Trim().Length > 0)
                            {
                                Entity.Telephone = row.GetCell(5).ToString();//联系方式
                            }
                            else {
                                Entity.Telephone = null;
                            }
                            if (row.GetCell(6) != null && row.GetCell(6).ToString().Trim().Length > 0)
                            {
                                Entity.Birthday = Convert.ToDateTime(row.GetCell(6).ToString());

                            }
                            else {
                                Entity.Birthday = null;
                            }
                            if (row.GetCell(7) != null && row.GetCell(7).ToString().Trim().Length > 0)
                            {
                                Entity.DepartmentId = row.GetCell(7).ToString();
                            }
                            if (row.GetCell(8) != null && row.GetCell(8).ToString().Trim().Length > 0)
                            {
                                role.Id = IdHelper.GetId();
                                role.CreateTime = DateTime.Now;
                                role.Deleted = false;
                                role.UserId = Entity.Id;
                                role.RoleId = row.GetCell(8).ToString();
                            }
                            if (row.GetCell(9) != null && row.GetCell(9).ToString().Trim().Length > 0)
                            {
                                Entity.UserPost = row.GetCell(9).ToString();
                            }
                            DataUser.Add(Entity);
                            liststr.Add(Entity.UserCode + "," + Entity.RealName);
                            DataRole.Add(role);
                        }
                    }


                    //通过用户编号判断重复
                    var UserCodes = DataUser.Select(s => s.UserCode).Select(s => s.Trim()).Distinct().ToList();
                    var UserCode = _userBus.GetQueryable<Base_User>().Where(w => UserCodes.Contains(w.UserCode)).ToDictionary(k => k.Id, v => v.UserCode);
                    //通过成品编号绑定物料主键ID

                    ///查询部门
                    var listContactsId = DataUser.Select(s => s.DepartmentId).Select(s => s.Trim()).Distinct().ToList();
                    var ProjectId = _userBus.GetQueryable<Base_Department>().Where(w => listContactsId.Contains(w.Name)).ToDictionary(k => k.Id, v => v.Name);
                    ///查询角色
                    var listRole = DataRole.Select(s => s.RoleId).Select(s => s.Trim()).Distinct().ToList();
                    var listRoles = _userBus.GetQueryable<Base_Role>().Where(w => listRole.Contains(w.RoleName)).ToDictionary(k => k.Id, v => v.RoleName);
                    foreach (var item in DataUser)
                    {


                        if (ProjectId.ContainsValue(item.DepartmentId.Trim()))
                        {
                            item.DepartmentId = ProjectId.FirstOrDefault(w => w.Value.Contains(item.DepartmentId.Trim())).Key;
                            var aa = await _Dept.GetOperatorGongChang(item.DepartmentId);
                            item.FactoryId = aa.DetpId;
                        }
                        else
                        {
                            return Error("所属部门不存在" + item.DepartmentId);
                        }
                    }
                    if (DataUser.Count > 0)
                    {
                        foreach (var itemss in DataUser)
                        {

                            foreach (var items in DataRole)
                            {
                                if (listRoles.ContainsValue(items.RoleId.Trim()))
                                {
                                    items.RoleId = listRoles.FirstOrDefault(w => w.Value.Contains(items.RoleId.Trim())).Key;
                                }

                            }
                        }
                        try
                        {
                            await _userBus.AddUserExlAsync(DataUser);
                            await _userBus.AddUserRoleExlAsync(DataRole);
                        }
                        catch (Exception ex)
                        {
                            return Error("第" + CountRow + "行");
                        }
                        ReturnValue = $"数据导入成功,共导入{CountRow - 1}条数据。";

                    }
                }
                if (!flag)
                {
                    return Error(ReturnValue = "数A据存在问题！" + ReturnValue);
                }
            }



            catch (Exception EX)
            {
                return Error("数据异常！");
            }
            return Success(ReturnValue);
        }

      public static string GetMD5(String input)
        {
            string cl = input;
            string pwd = "";
            MD5 md5 = MD5.Create();//实例化一个md5对像
                                   // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 

                pwd = pwd + s[i].ToString("X");

            }
            return pwd;
        }


        /// <summary>
        /// 用户导入模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NoCheckJWT]
        public IActionResult ExportToExcel()
        {
            //创建EXCEL工作薄
            IWorkbook workBook = new XSSFWorkbook();
            //创建sheet1文件表
            ISheet sheet = workBook.CreateSheet("用户信息模板");



            var expDir = string.Format("{0}Export\\{1}", System.AppDomain.CurrentDomain.BaseDirectory,
                    DateTime.Now.ToString("yyyyMM"));

            if (!Directory.Exists(expDir)) Directory.CreateDirectory(expDir);

            string filePath = string.Format("用户信息模板.xlsx", expDir, DateTime.Now.ToString("yyyyMMddHHmmss"));
            #region 创建Excel表头(sheet1)
            //创建表头
            IRow header = sheet.CreateRow(0);

            ICell cell = header.CreateCell(0);
            cell.SetCellValue("用户编号");
            cell = header.CreateCell(1);
            cell.SetCellValue("用户名");
            cell = header.CreateCell(2);
            cell.SetCellValue("用户密码");
            cell = header.CreateCell(3);
            cell.SetCellValue("姓名");
            cell = header.CreateCell(4);
            cell.SetCellValue("性别");
            cell = header.CreateCell(5);
            cell.SetCellValue("联系方式");
            cell = header.CreateCell(6);
            cell.SetCellValue("出生日期");
            cell = header.CreateCell(7);
            cell.SetCellValue("所属部门");
            cell = header.CreateCell(8);
            cell.SetCellValue("所属角色");
            cell = header.CreateCell(9);
            cell.SetCellValue("职务");
            #endregion
            //工作流写入，通过流的方式进行创建生成文件
            using (MemoryStream stream = new MemoryStream())
            {
                workBook.Write(stream);
                byte[] buffer = stream.ToArray();
                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", string.Format("用户信息模板.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss")));
            }

        }

        /// <summary>
        /// 通过钉钉id获取用户
        /// </summary>
        [HttpPost]
        [NoCheckJWT]
        public async Task<Base_UserDTO> GetDataListUserId(string DingUserId) {
            return await _userBus.GetDataDingUserIdAsyncUser(DingUserId);
        }


        [HttpPost]
        public async Task<List<Base_UserItemDTO>> GetItemUserList(string Deptid) {
            var res= await _userBus.GetItemUserList(Deptid);
            return res;
        }
        /// <summary>
        /// PDA员工头像上传
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task UploadAvatar(UserImgFile Data) {
            await _userBus.UploadAvatar(Data);
        }

    }
}